package gold.digger;

import gold.utils.InputUtil;
import org.stringtemplate.v4.ST;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1380 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {

        //        在同一行的所有元素中最小
        //        在同一列的所有元素中最大
        public List<Integer> luckyNumbers(int[][] matrix) {
            Set<String> rowMin = new HashSet<>();
            Set<String> colMax = new HashSet();

            for (int i = 0; i < matrix.length; i++) {
                int curRowMin = Integer.MAX_VALUE, pos = -1;
                for (int j = 0; j < matrix[0].length; j++) {
                    if (matrix[i][j] <= curRowMin) {
                        pos = j;
                        curRowMin = matrix[i][j];
                    }
                }

                rowMin.add(i + "_" + pos);
            }

            for (int j = 0; j < matrix[0].length; j++) {
                int curColMax = Integer.MIN_VALUE, pos = -1;
                for (int i = 0; i < matrix.length; i++) {
                    if (matrix[i][j] >= curColMax) {
                        pos = i;
                        curColMax = matrix[i][j];
                    }
                }

                colMax.add(pos + "_" + j);
            }

            List<Integer> ans = new ArrayList<>();
            for (String max : colMax) {
                if (rowMin.contains(max)) {
                    int x = Integer.parseInt(max.split("_")[0]), y = Integer.parseInt(max.split("_")[1]);
                    ans.add(matrix[x][y]);
                }
            }

            return ans;
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.luckyNumbers(InputUtil.toDoubleIntegerArray("[[3,7,8],[9,11,13],[15,16,17]]")));
        System.out.println(solution.luckyNumbers(InputUtil.toDoubleIntegerArray("[[1,10,4,2],[9,3,8,7],[15,16,17,12]]")));
        System.out.println(solution.luckyNumbers(InputUtil.toDoubleIntegerArray("[[7,8],[1,2]]")));
    }

    public static void main(String[] args) throws Exception {
        LC1380 an = new LC1380();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
